import React, {useEffect, useState} from 'react';
import {FooterToolbar, PageContainer} from '@ant-design/pro-layout';
import {isSuccess} from "@/utils/utils";
import {
  ProForm,
  ProFormMoney, ProFormRadio,
  ProFormSelect,
  ProFormSwitch,
  ProFormText
} from "@ant-design/pro-form";
import styles from './style.less';
import {Card, Col, Form, Row, Select} from "antd";
import {OpResourcesManager, UserManager} from "@/services/api-functions";
import UploadForm from "@/components/UploadForm";
import {LabelDto, OssPojo} from "@/services/api-types";
import {handleResourceEdit} from "@/pages/resource/list";
import {history} from "umi";
import {SYS_ENUMS} from "@/utils/constants";
import AssociateSelect from "@/components/AssociateSelect/AssociateSelect";
import {queryDictionaryMap} from "@/data-hooks/dictionary-hooks";

const ResourceEdit: React.FC<any> = (props) => {
  const {match: {params: {id}}} = props;

  const [formRef] = Form.useForm()
  const [colors, setColors] = useState<LabelDto[]>([])
  const [paymentType, setPaymentType] = useState<'FREE'|'PAY'>("FREE")
  const [associated, setAssociated] = useState<any>(null);
  const [visible, setVisible] = useState<boolean>(false);
  const [detailImage, setDetailImage] = useState<OssPojo>();
  const [resource, setResources] = useState<any>(null);
  const [cover, setCover] = useState<OssPojo>();
  const [previewsList, setPreviewsList] = useState<OssPojo[]>([]);
  const [resourcesAttachment, setResourcesAttachment] = useState<OssPojo>();
  const [dictionaryMap, setDictionaryMap] = useState<any>({});

  const queryResourceDetail = (id: any) => {
    if (id) {
      OpResourcesManager.resourcesDetail(id).then(({code, data}) => {
        if (isSuccess(code)) {
          setResources(data)
          if (data.cover) {
            setCover(data.cover)
          }
          if (data.detailImage) {
            setDetailImage(data.detailImage)
          }
          if (data.resourcesAttachment) {
            setResourcesAttachment(data.resourcesAttachment)
          }
          if (data.previewsList) {
            setPreviewsList(data.previewsList)
          }
          if (data.paymentType) {
            setPaymentType(data.paymentType)
          }
          if(data.associated){
            setAssociated(data.associated)
          }
          setColors(data.colors ?? [])

          formRef?.setFieldsValue({
            attachmentSize: data.attachmentSize,
            classification: data.classification,
            cloudAttachment: data.cloudAttachment,
            membersFree: data.membersFree,
            originalPrice: data.originalPrice,
            paymentType: data.paymentType,
            sellingPrice: data.sellingPrice,
            title: data.title,
            userId: data.userId,
            cover: data.cover ? [data.cover] : [],
            resourcesAttachment: data.resourcesAttachment ? [data.resourcesAttachment] : [],
            detailImage: data.detailImage ? [data.detailImage] : [],
            previewsList: data?.previewsList ?? [],
            labels: data?.labelList?.map((label: any) => label?.name) ?? []
          })
        }
      })
    }
  }

  useEffect(() => queryResourceDetail(id), [id])

  // @ts-ignore
  useEffect(async () => {
    const map = await queryDictionaryMap();
    setDictionaryMap(map ?? {})
  }, [])

  const onFinish = async (values: Record<string, any>) => {
    if (await handleResourceEdit(values, resource, cover, paymentType, detailImage, previewsList, resourcesAttachment, colors, associated)) {
      history.push('/resource/list')
    }
  };

  const onChange = async ({target: {value}}: any) => {
    if(value){
      if (colors.some(color => color.name == value)) {
        setColors(colors.filter(color => color.name !== value))
      } else {
        setColors([...colors, {name: value}])
      }
    }
  };

  const labelClick = (name: string) => {
    let labels = formRef?.getFieldValue('labels') ?? []
    if (!labels.some((labelName: any) => labelName === name)) {
      formRef?.setFieldsValue({
        labels: [...labels, name]
      })
    }
  }

  return (
    <ProForm
      layout="vertical"
      hideRequiredMark
      submitter={{
        render: (props, dom) =><FooterToolbar>{dom}</FooterToolbar>,
      }}
      form={formRef}
      initialValues={{}}
      onFinish={onFinish}
      onValuesChange={v => {
        if(v.paymentType){
          setPaymentType(v.paymentType)
        }
      }}
    >
      <PageContainer>
        <Card title={`${id?'编辑':'添加'}资源`} className={styles.card} bordered={false}>
          <Row gutter={16}>
            <Col lg={12} md={12} sm={24}>
              <ProFormText label='标题' required rules={[{required: true, message: '请填写标题',},]} name="title"/>
            </Col>
          </Row>
          <Row gutter={16}>
            <Col lg={12} md={12} sm={24}>
              <ProFormSelect label='所属设计师' name='userId' required rules={[{required: true, message: '请设置所属设计师',},]}
                             request={async (params) => {
                               const {code, data} = await UserManager.simpleUserQuery({
                                 current: 1,
                                 pageSize: 20,
                                 nickName: params.keyWords ?? '',
                               })
                               return isSuccess(code) ? (data.data ?? []).map((item: any) => {
                                 const {id, nickName, phone} = item
                                 return {label: `${nickName}(${phone ?? '暂无手机号'})`, value: id}
                               }) : []
                             }} showSearch/>
            </Col>
          </Row>
          <Row gutter={16}>
            <Col lg={6} md={12} sm={24}>
              <ProFormSelect label='分类' required rules={[{required: true, message: '请填选择分类',},]} name='classification'
                             initialValue={SYS_ENUMS.RESOURCE_CLASSIFICATION.TEMPLATE.value}
                             options={Object.values(SYS_ENUMS.RESOURCE_CLASSIFICATION)}/>
            </Col>
          </Row>
          <Row gutter={16}>
            <Col lg={12} md={12} sm={24}>
              <ProFormSelect label='标签' name='labels' mode='tags'/>
              <div style={{color:'gray'}}>最多不超过五个标签</div>
              <p>
                <strong>行业：</strong> {dictionaryMap?.LABEL_INDUSTRY?.map((label: any)=><a key={label.key} onClick={()=>labelClick(label.name)} style={{marginLeft: 30}}>{label.name}</a>)}
              </p>
              <p>
                <strong>用途：</strong> {dictionaryMap?.LABEL_USE?.map((label: any)=><a key={label.key} onClick={()=>labelClick(label.name)} style={{marginLeft: 30}}>{label.name}</a>)}
              </p>
            </Col>
          </Row>
          <Row gutter={16}>
            <Col lg={12} md={12} sm={24}>

            </Col>
          </Row>
          <Row gutter={16}>
            <Col lg={12} md={12} sm={24}>
              <ProFormRadio.Group label={`颜色（${colors.length > 0 ? ('当前选中：' + colors.map(color => color.name).join(',')) : '请选择'}）`}>
                <ProFormRadio.Button value='红色' style={{backgroundColor: 'red', marginRight: 20}} onClick={onChange}/>
                <ProFormRadio.Button value='橙色' style={{backgroundColor: 'orange', marginRight: 20}} onClick={onChange}/>
                <ProFormRadio.Button value='黄色' style={{backgroundColor: 'yellow', marginRight: 20}} onClick={onChange}/>
                <ProFormRadio.Button value='绿色' style={{backgroundColor: 'green', marginRight: 20}} onClick={onChange}/>
                <ProFormRadio.Button value='蓝色' style={{backgroundColor: 'blue', marginRight: 20}} onClick={onChange}/>
                <ProFormRadio.Button value='紫色' style={{backgroundColor: 'purple', marginRight: 20}} onClick={onChange}/>
                <ProFormRadio.Button value='黑色' style={{backgroundColor: 'black', marginRight: 20}} onClick={onChange}/>
                <ProFormRadio.Button value='白色' style={{backgroundColor: 'white', marginRight: 20}} onClick={onChange}/>
                <ProFormRadio.Button value='灰色' style={{backgroundColor: 'gray', marginRight: 20}} onClick={onChange}/>
                <ProFormRadio.Button value='金色' style={{backgroundColor: '#dac393', marginRight: 20}} onClick={onChange}/>
                <ProFormRadio.Button value='深蓝' style={{backgroundColor: '#1d4181', marginRight: 20}} onClick={onChange}/>
                <ProFormRadio.Button value='粉色' style={{backgroundColor: 'pink', marginRight: 20}} onClick={onChange}/>
              </ProFormRadio.Group>
            </Col>
          </Row>
          <Row gutter={16}>
            <Col lg={12} md={12} sm={24}>
              <ProFormRadio.Group label='付费类型' required name="paymentType">
                <ProFormRadio.Button value='FREE'
                                     style={paymentType === 'FREE' ? {backgroundColor: '#40a9ff', color: 'white'} : {}}
                                     onClick={() => setPaymentType('FREE')}>免费</ProFormRadio.Button>
                <ProFormRadio.Button value='PAY'
                                     style={paymentType === 'PAY' ? {backgroundColor: '#40a9ff', color: 'white'} : {}}
                                     onClick={() => setPaymentType('PAY')}>付费</ProFormRadio.Button>
              </ProFormRadio.Group>
            </Col>
          </Row>
          {
            paymentType == 'PAY' && <Row gutter={16}>
              <Col lg={12} md={12} sm={24}>
                <ProFormSwitch label='是否加入会员免费' unCheckedChildren='关闭' checkedChildren='开启' initialValue={false} name='membersFree' required/>
              </Col>
            </Row>
          }

          {
            paymentType == 'PAY' && <Row gutter={16}>
              <Col lg={12} md={12} sm={24}>
                <ProFormMoney label='资源价格' name='sellingPrice' rules={[{required: true, message: '请输入资源价格',},]}/>
              </Col>
            </Row>
          }

          {
            paymentType == 'PAY' && <Row gutter={16}>
              <Col lg={12} md={12} sm={24}>
                <ProFormMoney label='原价' name='originalPrice'/>
              </Col>
            </Row>
          }

          <Row gutter={16}>
            <Col lg={12} md={12} sm={24}>
              <UploadForm name='cover' type='public' max={1} rules={[{required: true, message: '请上传封面',},]} required={true}
                          accept='.jpg,.jpeg,.bmp,.gif,.png' label='封面' success={file => setCover(file)}
                          remove={() => setCover(undefined)}/>
            </Col>
          </Row>
          <Row gutter={16}>
            <Col lg={12} md={12} sm={24}>
              <UploadForm name='previewsList' type='public' max={7} rules={[{required: true, message: '请上传介绍图片',},]}
                          remove={arr => setPreviewsList(arr)}  fileList={previewsList}
                          required={true} accept='.jpg,.jpeg,.bmp,.gif,.png' label='介绍图片' multiple={true}
                          success={file => setPreviewsList([...previewsList, file])}/>

            </Col>
          </Row>
          <Row gutter={16}>
            <Col lg={12} md={12} sm={24}>
              <UploadForm name='detailImage' type='public' max={1} rules={[{required: true, message: '请上传长图',},]}
                          required={true} accept='.jpg,.jpeg,.bmp,.gif,.png' label='长图' success={file => setDetailImage(file)}
                          remove={() => setDetailImage(undefined)}/>
            </Col>
          </Row>
          <Row gutter={16}>
            <Col lg={12} md={12} sm={24}>
              <UploadForm name='resourcesAttachment' type='formal' max={1} label='附件' drag={true} preview='open'
                          success={file => setResourcesAttachment(file)} remove={() => setResourcesAttachment(undefined)}/>
            </Col>
          </Row>
          <Row gutter={16}>
            <Col lg={12} md={12} sm={24}>
              <ProFormText label='网盘链接' name="cloudAttachment"/>
            </Col>
          </Row>
          <Row gutter={16}>
            <Col lg={6} md={12} sm={24}>
              <Form.Item label='关联资源/文章'>
                <Select style={{width: '100%'}} onClick={() => setVisible(true)} placeholder='请选择'
                        value={associated ? associated.id : undefined}>
                  {
                    associated && <Select.Option value={associated.id}>{associated.title}</Select.Option>
                  }
                </Select>
              </Form.Item>
            </Col>
          </Row>
        </Card>
        <AssociateSelect useType='RESOURCES' initType='WORKS' visible={visible} title='请选择关联的文章/作品'
                         onCancel={() => setVisible(false)}
                         onSelect={(type: string, select: any) => setAssociated({
                           id: select.id,
                           title: select.title,
                           cover: select.cover,
                           type
                         })}/>
      </PageContainer>
    </ProForm>
  );
};

export default ResourceEdit;
